<template>
  <div class="admin-admission">
    <div class="page-header">
      <h1>录取管理</h1>
      <p>管理学生录取结果和通知</p>
    </div>

    <!-- 搜索筛选 -->
    <el-card class="filter-card" shadow="never">
      <el-form :model="searchForm" :inline="true">
        <el-form-item label="院校">
          <el-select v-model="searchForm.schoolId" placeholder="选择院校" clearable>
            <el-option v-for="school in schools" :key="school.id" :label="school.name" :value="school.id" />
          </el-select>
        </el-form-item>
        <el-form-item label="专业">
          <el-select v-model="searchForm.majorId" placeholder="选择专业" clearable>
            <el-option v-for="major in majors" :key="major.id" :label="major.name" :value="major.id" />
          </el-select>
        </el-form-item>
        <el-form-item label="录取状态">
          <el-select v-model="searchForm.admissionStatus" placeholder="录取状态" clearable>
            <el-option label="录取" value="admitted" />
            <el-option label="候补" value="waitlist" />
            <el-option label="未录取" value="rejected" />
          </el-select>
        </el-form-item>
        <el-form-item label="关键词">
          <el-input v-model="searchForm.keyword" placeholder="姓名/身份证" clearable />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="loadAdmissions">搜索</el-button>
          <el-button @click="resetSearch">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 数据表格 -->
    <el-card shadow="never">
      <template #header>
        <div class="card-header">
          <span>录取结果</span>
          <div>
            <el-button type="primary" @click="generateResults">生成录取结果</el-button>
            <el-button type="success" @click="publishSelected" :disabled="selectedIds.length === 0">
              发布选中
            </el-button>
            <el-button type="warning" @click="sendNotices">发送通知</el-button>
          </div>
        </div>
      </template>

      <el-table 
        v-loading="loading" 
        :data="admissions" 
        stripe
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55" />
        <el-table-column prop="studentName" label="学生姓名" />
        <el-table-column prop="idCard" label="身份证号" />
        <el-table-column prop="phone" label="联系电话" />
        <el-table-column prop="totalScore" label="总分" sortable />
        <el-table-column prop="examScore" label="校测成绩" sortable />
        <el-table-column prop="finalScore" label="最终成绩" sortable />
        <el-table-column prop="rankInMajor" label="专业排名" sortable />
        <el-table-column prop="admissionStatus" label="录取状态">
          <template #default="{ row }">
            <el-tag :type="getAdmissionStatusType(row.admissionStatus)">
              {{ getAdmissionStatusText(row.admissionStatus) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="confirmStatus" label="确认状态">
          <template #default="{ row }">
            <el-tag :type="getConfirmStatusType(row.confirmStatus)">
              {{ getConfirmStatusText(row.confirmStatus) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="noticeSent" label="通知状态">
          <template #default="{ row }">
            <el-tag :type="row.noticeSent ? 'success' : 'warning'">
              {{ row.noticeSent ? '已发送' : '未发送' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="publishTime" label="发布时间" />
        <el-table-column label="操作" width="200">
          <template #default="{ row }">
            <el-button size="small" @click="viewDetail(row)">查看</el-button>
            <el-button size="small" type="primary" @click="editAdmission(row)">编辑</el-button>
            <el-button 
              v-if="!row.noticeSent" 
              size="small" 
              type="success" 
              @click="sendSingleNotice(row)"
            >
              发通知
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-wrapper">
        <el-pagination
          v-model:current-page="pagination.page"
          v-model:page-size="pagination.size"
          :total="pagination.total"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="loadAdmissions"
          @current-change="loadAdmissions"
        />
      </div>
    </el-card>

    <!-- 生成录取结果对话框 -->
    <el-dialog v-model="generateDialogVisible" title="生成录取结果" width="500px">
      <el-form :model="generateForm" label-width="120px">
        <el-form-item label="选择院校" required>
          <el-select v-model="generateForm.schoolId" placeholder="请选择院校">
            <el-option v-for="school in schools" :key="school.id" :label="school.name" :value="school.id" />
          </el-select>
        </el-form-item>
        <el-form-item label="选择专业" required>
          <el-select v-model="generateForm.majorId" placeholder="请选择专业">
            <el-option v-for="major in generateMajors" :key="major.id" :label="major.name" :value="major.id" />
          </el-select>
        </el-form-item>
        <el-form-item label="录取人数" required>
          <el-input-number v-model="generateForm.admissionCount" :min="1" :max="1000" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="generateDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="confirmGenerate">确定生成</el-button>
      </template>
    </el-dialog>

    <!-- 编辑录取状态对话框 -->
    <el-dialog v-model="editDialogVisible" title="编辑录取结果" width="600px">
      <el-form :model="editForm" label-width="120px">
        <el-form-item label="学生姓名">
          <span>{{ editForm.studentName }}</span>
        </el-form-item>
        <el-form-item label="录取状态">
          <el-select v-model="editForm.admissionStatus">
            <el-option label="录取" value="admitted" />
            <el-option label="候补" value="waitlist" />
            <el-option label="未录取" value="rejected" />
          </el-select>
        </el-form-item>
        <el-form-item label="总分">
          <el-input-number v-model="editForm.totalScore" :min="0" />
        </el-form-item>
        <el-form-item label="校测成绩">
          <el-input-number v-model="editForm.examScore" :min="0" />
        </el-form-item>
        <el-form-item label="最终成绩">
          <el-input-number v-model="editForm.finalScore" :min="0" />
        </el-form-item>
        <el-form-item label="专业排名">
          <el-input-number v-model="editForm.rankInMajor" :min="1" />
        </el-form-item>
        <el-form-item label="备注">
          <el-input v-model="editForm.remark" type="textarea" :rows="3" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="editDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitEdit">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, watch } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import api from '@/api'

// 响应式数据
const loading = ref(false)
const admissions = ref([])
const schools = ref([])
const majors = ref([])
const generateMajors = ref([])
const selectedIds = ref([])

const searchForm = reactive({
  schoolId: '',
  majorId: '',
  admissionStatus: '',
  keyword: ''
})

const pagination = reactive({
  page: 1,
  size: 20,
  total: 0
})

const generateDialogVisible = ref(false)
const generateForm = reactive({
  schoolId: '',
  majorId: '',
  admissionCount: 30
})

const editDialogVisible = ref(false)
const editForm = reactive({
  id: null,
  studentName: '',
  admissionStatus: '',
  totalScore: 0,
  examScore: 0,
  finalScore: 0,
  rankInMajor: 0,
  remark: ''
})

// 方法
const loadAdmissions = async () => {
  loading.value = true
  try {
    const params = {
      page: pagination.page,
      size: pagination.size,
      ...searchForm
    }
    const { data } = await api.get('/admission/admin', { params })
    admissions.value = data.records || []
    pagination.total = data.total || 0
  } catch (error) {
    ElMessage.error('加载失败')
  } finally {
    loading.value = false
  }
}

const loadSchools = async () => {
  try {
    const { data } = await api.get('/schools')
    schools.value = data.records || []
  } catch (error) {
    console.error('加载院校失败:', error)
  }
}

const loadMajors = async () => {
  if (searchForm.schoolId) {
    try {
      const { data } = await api.get('/majors', { 
        params: { schoolId: searchForm.schoolId } 
      })
      majors.value = data.records || []
    } catch (error) {
      console.error('加载专业失败:', error)
    }
  } else {
    majors.value = []
  }
}

const loadGenerateMajors = async () => {
  if (generateForm.schoolId) {
    try {
      const { data } = await api.get('/majors', { 
        params: { schoolId: generateForm.schoolId } 
      })
      generateMajors.value = data.records || []
    } catch (error) {
      console.error('加载专业失败:', error)
    }
  } else {
    generateMajors.value = []
  }
}

const resetSearch = () => {
  Object.assign(searchForm, {
    schoolId: '',
    majorId: '',
    admissionStatus: '',
    keyword: ''
  })
  majors.value = []
  loadAdmissions()
}

const handleSelectionChange = (selection) => {
  selectedIds.value = selection.map(item => item.id)
}

const generateResults = () => {
  Object.assign(generateForm, {
    schoolId: '',
    majorId: '',
    admissionCount: 30
  })
  generateDialogVisible.value = true
}

const confirmGenerate = async () => {
  try {
    await api.post('/admission/generate', null, {
      params: {
        schoolId: generateForm.schoolId,
        majorId: generateForm.majorId,
        admissionCount: generateForm.admissionCount
      }
    })
    ElMessage.success('录取结果生成成功')
    generateDialogVisible.value = false
    loadAdmissions()
  } catch (error) {
    ElMessage.error('录取结果生成失败')
  }
}

const publishSelected = async () => {
  try {
    await ElMessageBox.confirm('确认发布选中的录取结果？', '确认发布')
    await api.put('/admission/publish', null, {
      params: { ids: selectedIds.value }
    })
    ElMessage.success('发布成功')
    loadAdmissions()
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('发布失败')
    }
  }
}

const viewDetail = (row) => {
  ElMessage.info('查看详情功能待实现')
}

const editAdmission = (row) => {
  Object.assign(editForm, {
    id: row.id,
    studentName: row.studentName,
    admissionStatus: row.admissionStatus,
    totalScore: row.totalScore,
    examScore: row.examScore,
    finalScore: row.finalScore,
    rankInMajor: row.rankInMajor,
    remark: row.remark
  })
  editDialogVisible.value = true
}

const submitEdit = async () => {
  try {
    await api.put(`/admission/${editForm.id}`, editForm)
    ElMessage.success('更新成功')
    editDialogVisible.value = false
    loadAdmissions()
  } catch (error) {
    ElMessage.error('更新失败')
  }
}

const sendSingleNotice = async (row) => {
  try {
    await ElMessageBox.confirm('确认发送录取通知？', '确认发送')
    await api.post(`/admission/${row.id}/notice`)
    ElMessage.success('通知发送成功')
    loadAdmissions()
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('通知发送失败')
    }
  }
}

const sendNotices = () => {
  ElMessage.info('批量发送通知功能待实现')
}

const getAdmissionStatusType = (status) => {
  const map = {
    admitted: 'success',
    waitlist: 'warning',
    rejected: 'danger'
  }
  return map[status] || 'info'
}

const getAdmissionStatusText = (status) => {
  const map = {
    admitted: '录取',
    waitlist: '候补',
    rejected: '未录取'
  }
  return map[status] || status
}

const getConfirmStatusType = (status) => {
  const map = {
    pending: 'warning',
    confirmed: 'success',
    declined: 'danger'
  }
  return map[status] || 'info'
}

const getConfirmStatusText = (status) => {
  const map = {
    pending: '待确认',
    confirmed: '已确认',
    declined: '已放弃'
  }
  return map[status] || status
}

// 监听
watch(() => searchForm.schoolId, () => {
  searchForm.majorId = ''
  loadMajors()
})

watch(() => generateForm.schoolId, () => {
  generateForm.majorId = ''
  loadGenerateMajors()
})

// 初始化
onMounted(() => {
  loadAdmissions()
  loadSchools()
})
</script>

<style lang="scss" scoped>
.admin-admission {
  .page-header {
    margin-bottom: 20px;
    
    h1 {
      margin: 0 0 8px 0;
      font-size: 24px;
      color: #303133;
    }
    
    p {
      margin: 0;
      color: #909399;
    }
  }
  
  .filter-card {
    margin-bottom: 20px;
  }
  
  .card-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
  }
  
  .pagination-wrapper {
    margin-top: 20px;
    text-align: right;
  }
}
</style>